package traductor;


import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextArea;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class TranslatorEngine {

    // The Firefox driver supports  javascript
    WebDriver driver = new FirefoxDriver();


    public String translateText() {
        WebElement input = driver.findElement(By.xpath("//*[@id='source']"));
        waitForElementPresent("//*[@id='source']");
        input.clear();
        input.sendKeys(getSourceText());
        WebElement botao = driver.findElement(By.xpath("//*[@id='gt-submit']"));
        botao.click();
        WebElement element = driver.findElement(By.xpath("//*[@id='result_box']"));
        waitTime();
        return element.getText();
    }

    private void waitTime() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(TranslatorEngine.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void waitForElementPresent(String xpath) {
        WebElement element = null;
        while (element == null) {
            element = driver.findElement(By.xpath(xpath));
            waitTime();
        }
    }

    public void stop() {        
        driver.close();
  
    }

    public void start() {
        driver.get("http://translate.google.com.br/#en|pt|Dont close this window"); 
    }

    public String getSourceText() {
        //get the system clipboard
        Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        // get the contents on the clipboard in a
        // transferable object
        Transferable clipboardContents = systemClipboard.getContents(null);
        // check if clipboard is empty
        if (clipboardContents == null) {
            return ("Clipboard is empty!!!");
        } else {
            try {
                // see if DataFlavor of
                // DataFlavor.stringFlavor is supported
                if (clipboardContents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                    // return text content
                    String returnText = (String) clipboardContents.getTransferData(DataFlavor.stringFlavor);
                    return returnText;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}